<?php
namespace app\api\controller;


use EasyWeChat\MiniApp\Application;
use think\facade\Log;

class WeMiniProApi extends Base
{

    public function signature(){
        $config = config('wechat.mini_program.default');
        $token = $config["token"]; // 和微信后台一致
        // 获取请求参数
        $signature = input('signature');
        $timestamp = input('timestamp');
        $nonce = input('nonce');
        $echostr = input('echostr');
        // 签名验证
        $tmpArr = [$token, $timestamp, $nonce];
        sort($tmpArr, SORT_STRING); // 字典排序
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        Log::info($signature.'---'.$timestamp.'----'.$nonce.'---'.$echostr);
        Log::info($tmpStr);
        Log::info($token);

        // 如果签名验证通过，返回 echostr，否则返回错误信息
        if ($tmpStr === $signature) {
            echo $echostr; // 微信需要返回这个字符串
        }else{
            echo  'Token verification failed';
        }
        exit;
    }


    public function sendMsg(){
        /*
         * const tmplIds = ['NZWM1hrYLa1W-3ojwwn9FH_GAQbP65VFT2JVjbXUH4s'];
    wx.requestSubscribeMessage({
         // 替换为你实际的模板 ID
        tmplIds: tmplIds,
        success(res) {
          // 用户允许订阅消息
          if (res[tmplIds[0]] === 'accept') {
            wx.showToast({
              title: '订阅成功',
            });
          } else {
            wx.showToast({
              title: '订阅被拒绝',
              icon: 'error',
            });
          }
          console.log('订阅消息结果:', res);
        },
        fail(err) {
          // 订阅失败
          console.error('订阅消息失败:', err);
          wx.showToast({
            title: '订阅失败',
            icon: 'error',
          });
        },
      });*/
        $config = config('wechat.mini_program.default');
        $app = new Application($config);

        // 订阅消息数据
        $data = [
            'touser'      => 'oXwma7aGv5kLUfB18W7RsqS_IxSg',
            'template_id' => 'NZWM1hrYLa1W-3ojwwn9FH_GAQbP65VFT2JVjbXUH4s', // 微信小程序订阅消息模板ID
            'page'        => 'pages/index/index', // 用户点击消息后跳转的页面
            'data'        => [
                'time2' => ['value' => '10:00'],
                'thing5'  => ['value' => '今天完成一套模拟考卷'],
                'thing6' => ['value' => '先完成每日一练，再做模拟卷'],
            ],
            'miniprogram_state' => 'formal', // 可选值：formal, trial, developer
            'lang'              => 'zh_CN', // 可选值：zh_CN, en_US, etc.
        ];

        try {
            $result = $app->getClient()->postJson('/cgi-bin/message/subscribe/send', $data);

            // 发送订阅消息
            //$result = $app->subscribe_message->send($data);

            return json_encode(['status' => 'success', 'data' => $result]);
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

}
